package com.xdq.spring.controller;

import com.fasterxml.jackson.databind.annotation.JsonAppend;
import com.xdq.spring.model.Engine;
import com.xdq.spring.service.EngineService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.List;
import java.util.Random;

@Controller
@RequestMapping("/engine")
public class EngineController {

    @Resource
    private EngineService engineService;

    @RequestMapping("/one/{brand}")
    public ModelAndView findByBrand(@PathVariable("brand") String brand){
        Engine engine= engineService.findByBrand(brand);
        ModelAndView modelAndView=new ModelAndView("engine");
        modelAndView.addObject("engine",engine);
        return modelAndView;
    }

    @RequestMapping("/list")
    public ModelAndView list(){
        List<Engine> engineList= engineService.list();
        ModelAndView modelAndView=new ModelAndView("list");
        modelAndView.addObject("engineList",engineList);
        return modelAndView;
    }

    @RequestMapping("/list2")
    public ModelAndView list2(){
        List<Engine> engineList= engineService.list();
        ModelAndView modelAndView=new ModelAndView("list2");
        modelAndView.addObject("engineList",engineList);
        return modelAndView;
    }

    @RequestMapping("/toadd")
    public String engineadd(@ModelAttribute("newEngine") Engine newEngine, Model model){
        return "toadd";
    }

    @RequestMapping("/add")
    public ModelAndView add(Engine newEngine){
        newEngine.setId(new Random().nextInt(100000));
        engineService.add(newEngine);

        List<Engine> engineList= engineService.list();
        ModelAndView modelAndView=new ModelAndView("list2");
        modelAndView.addObject("engineList",engineList);
        return modelAndView;
    }
}
